package edu.nf.ch07.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.nf.ch07.web.vo.ResultVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author wangl
 * @date 2025/5/14
 */
@WebFilter(urlPatterns = "/*")
public class AuthFilter implements Filter {

    /**
     * 放行的地址都保存在这个集合中
     */
    private static List<String> list;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        list = Arrays.asList("/auth", "/login.html", "/index.html");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //判断请求地址，如果是认证和登陆页面则直接放行
        String url = request.getRequestURI();
        if(list.contains(url)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //获取token认证
            String token = request.getHeader("auth");
            if(token != null && !token.isEmpty() && !token.equals("null")) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                //先判断是否是ajax请求，如果是则响应ResultVO
                //否则重定向到登陆页面
                String requestType = request.getHeader("X-Requested-With");
                if("XMLHttpRequest".equals(requestType)) {
                    //响应vo
                    ResultVO<String> vo = new ResultVO<>();
                    vo.setCode(HttpStatus.UNAUTHORIZED.value());
                    vo.setMessage("尚未登录");
                    response.setContentType("application/json");
                    //将vo转换成json字符串
                    String json = new ObjectMapper().writeValueAsString(vo);
                    response.getWriter().write(json);
                } else {
                    //重定向登陆页面
                    response.sendRedirect(request.getContextPath() + "/login.html");
                }
            }
        }
    }
}